package com.example.util;

import com.example.model.WxbGood;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Set;

@Component
public class GoodHandler {

    @Autowired
    private StringRedisTemplate redisTemplate;


    public void addToCache(List<WxbGood> good,int pageNum){
        String json = new Gson().toJson(good);

            redisTemplate.boundValueOps("goods"+pageNum).set(json);

    }

    /**
     * 从缓存取出商品信息
     * @return
     */
    public List<WxbGood> getFromCache(int pageNum){
        if(redisTemplate.hasKey("goods"+pageNum)){
            String json = redisTemplate.boundValueOps("goods"+pageNum).get();
            Type type =  new TypeToken<List<WxbGood>>(){}.getType();
            return new Gson().fromJson(json,type);
        }else{
            return null;
        }
    }

    public void deleteGood(){
        Set<String> keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);
    }


}
